/**
 * request工具方法
 * 兼容网关请求，宝盒网关请求
 */
import axios from 'axios'
import { Message } from 'element-ui'
import { HostName } from '@/configs/env'
import router from '@/router'
// import { getToken } from './auth'
// import store from '@/store'

axios.defaults.withCredentials = true
// axios.defaults.headers.common['Cookie'] = ''

function createService() {
	const axiosConfig = {
		baseURL: HostName, //存在一些场景，调用多个后端地址
		// timeout: 5000, // 超时时间
		withCredentials: true // 允许携带cookie
	}

	return axios.create(axiosConfig)
}

/**
 * 创建axios实例
 */
const service = createService()

// 请求2秒内的错误只提示一次
const errorMsg = function (text) {
	Message.error({
		message: text,
		type: 'error',
		duration: 3000,
		showClose: true
	})
}

service.interceptors.request.use(
	(config) => {
		// if (store.getters.token) {
		// let each request carry token
		// ['X-Token'] is a custom headers key
		// please modify it according to the actual situation
		// config.headers['COOKIE'] = getToken()
		// }
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// response拦截器
service.interceptors.response.use(
	(response) => {
		const res = response.data
		// 请求成功
		return response
	},
	(error) => {
		// 无权限
		if (error.response.status === 401) {
			router.push('/login')
		} else if (error.response.status === 500) {
			errorMsg('服务不可用')
		} else {
			console.log(`repsones error: ${error}`) // for debug
			errorMsg(error.response.data.Msg)
		}
		return Promise.reject(error)
	}
)

/**
 * get 请求
 * @param url
 * @param params
 */
async function get(url, params) {
	return await request({ url, params, method: 'get' })
}

/**
 * post 请求
 * @param url
 * @param requestData
 */
async function post(url, requestData, isForm) {
	if (isForm) {
		axios.defaults.headers['Content-Type'] = 'multipart/form-data'
	}
	return await request({ url, data: requestData, method: 'post' })
}

async function reqDelete(url, requestData) {
	return await request({ url: url, data: requestData, method: 'delete' })
}
async function request(config) {
	const { data } = await service(config)
	return data
}

request.post = post
request.get = get
request.delete = reqDelete

export default request
